package toXML;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import person.DayList;
import person.Interval;
import person.Person;
import person.PersonAchive;

public class SaveFamilyXML {

	public static void save(File f) throws FileNotFoundException,
			TransformerConfigurationException, SAXException {

		PrintWriter out = new PrintWriter(f);
		StreamResult streamResult = new StreamResult(out);
		SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory
				.newInstance();
		TransformerHandler hd = tf.newTransformerHandler();
		Transformer serializer = hd.getTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		hd.setResult(streamResult);
		hd.startDocument();
		AttributesImpl atts = new AttributesImpl();
		atts.addAttribute("", "", "Count", "CDATA", PersonAchive.getCount()
				+ "");
		hd.startElement("", "", "Family", atts);
		for (int i = 0; i < PersonAchive.getCount(); i++) {
			Person p = PersonAchive.getPerson(i);
			atts.clear();
			atts.addAttribute("", "", "FirstName", "CDATA", p.getName());
			atts.addAttribute("", "", "LastName", "CDATA", p.getLastName());
			atts.addAttribute("", "", "age", "CDATA", p.getAge() + "");
			atts.addAttribute("", "", "sex", "CDATA", p.getSex() + "");
			atts.addAttribute("", "", "RFID_ID", "CDATA", p.getrFid()
					.getSensorID()
					+ "");
			hd.startElement("", "", "Person", atts);
			atts.clear();
			if (p.getPlan() != null) {
				hd.startElement("", "", "Schedule", atts);
				for (int j = 0; j < 7; j++) {
					Interval iv = p.getPlan().getInterval(toDay(j));
					System.out.println(iv);
					if (iv != null) {
						atts.clear();
						atts.addAttribute("", "", "LeaveTime", "CDATA", iv
								.getStart());
						atts.addAttribute("", "", "HomeTime", "CDATA", iv
								.getEnd());
						hd.startElement("", "", toDay(j), atts);
						hd.endElement("", "", toDay(j));
					}
				}
				hd.endElement("", "", "Schedule");
			}
			hd.endElement("", "", "Person");
		}
		hd.endElement("", "", "Family");
		hd.endDocument();
	}

	private static String toDay(int j) {
		return (DayList.days[j]);

	}

}
